package com.common

import android.widget.Toast

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType

// 输入窗口
class InputBox {
    private var mMaxValue = Int.MAX_VALUE               // 允许输入的最大值
    private var mMinValue = Int.MIN_VALUE               // 允许输入的最小值
    private var mOnCancel: () -> Unit = {}              // 用户单击"取消"按钮事件
    private var mOnOKInt: (Int) -> Unit = {}            // 用户单击"确定"按钮事件（返回整数值）
    private var mOnOKString: (String) -> Unit = {}      // 用户单击"确定"按钮事件（返回字符串）
    private lateinit var mShow: MutableState<Boolean>   // 是否显示
    private lateinit var mText: MutableState<String>    // 用户输入的内容
    private var mTipText = ""                           // 提示文字

    /**
     * 界面布局（返回整数）。
     */
    @Composable
    fun Greeting(defaultValue: Int) {
        mShow = remember {
            mutableStateOf(false)
        }
        mText = remember {
            mutableStateOf(defaultValue.toString())
        }
        val focusRequester = remember {
            FocusRequester()
        }
        val inputInvalidValue = "输入的内容超出了允许范围，请重新输入。"

        if (mShow.value) {
            val context = LocalContext.current
            AlertDialog(
                onDismissRequest = {},
                text = {
                    OutlinedTextField(
                        modifier = Modifier
                            .fillMaxWidth()
                            .focusRequester(focusRequester),
                        label = {
                            Text(mTipText)
                        },
                        value = mText.value,
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Companion.Number),
                        onValueChange = {
                            mText.value = it
                        }
                    )
                },
                confirmButton = {
                    TextButton(onClick = {
                        // 检查输入的数字
                        var value: Int
                        try {
                            value = mText.value.toInt()
                        } catch (_: Exception) {
                            Toast.makeText(context, inputInvalidValue, Toast.LENGTH_LONG).show()
                            focusRequester.requestFocus()
                            return@TextButton
                        }
                        if (value < mMinValue || value > mMaxValue) {
                            Toast.makeText(context, inputInvalidValue, Toast.LENGTH_LONG).show()
                            focusRequester.requestFocus()
                            return@TextButton
                        }
                        this.mOnOKInt(value)

                        // 关闭窗口
                        mShow.value = false
                    }) {
                        Text(context.getString(android.R.string.ok))
                    }
                },
                dismissButton = {
                    TextButton(onClick = {
                        this.mOnCancel()

                        // 关闭窗口
                        mShow.value = false
                    }) {
                        Text(context.getString(android.R.string.cancel))
                    }
                }
            )
        }
    }

    /**
     * 界面布局（返回字符串）。
     */
    @Composable
    fun Greeting(defaultValue: String) {
        mShow = remember {
            mutableStateOf(false)
        }
        mText = remember {
            mutableStateOf(defaultValue)
        }

        val context = LocalContext.current
        if (mShow.value) {
            AlertDialog(
                onDismissRequest = {},
                text = {
                    OutlinedTextField(
                        modifier = Modifier.fillMaxWidth(),
                        label = {
                            Text(mTipText)
                        },
                        value = mText.value,
                        onValueChange = {
                            mText.value = it
                        }
                    )
                },
                confirmButton = {
                    TextButton(onClick = {
                        this.mOnOKString(mText.value)

                        // 关闭窗口
                        mShow.value = false
                    }) {
                        Text(context.getString(android.R.string.ok))
                    }
                },
                dismissButton = {
                    TextButton(onClick = {
                        this.mOnCancel()

                        // 关闭窗口
                        mShow.value = false
                    }) {
                        Text(context.getString(android.R.string.cancel))
                    }
                }
            )
        }
    }

    /**
     * 显示。
     * @param displayValue  编辑框上显示的默认值
     * @param maxValue      允许输入的最大值
     * @param minValue      允许输入的最小值
     * @param onCancel      用户单击"取消"按钮事件
     * @param onOKInt       用户单击"确定"按钮事件（返回整数值）
     * @param tipText       提示文字
     */
    fun show(
        displayValue: Int = 0,
        maxValue: Int = Int.MAX_VALUE,
        minValue: Int = Int.MIN_VALUE,
        onCancel: () -> Unit = {},
        onOKInt: (Int) -> Unit = {},
        tipText: String = ""
    ) {
        mText.value = displayValue.toString()
        mMaxValue = maxValue
        mMinValue = minValue
        mOnCancel = onCancel
        mOnOKInt = onOKInt
        mTipText = tipText
        mShow.value = true
    }

    /**
     * 显示。
     * @param displayValue  编辑框上显示的默认值
     * @param onCancel      用户单击"取消"按钮事件
     * @param onOKString    用户单击"确定"按钮事件（返回字符串）
     * @param tipText       提示文字
     */
    fun show(
        displayValue: String = "",
        onCancel: () -> Unit = {},
        onOKString: (String) -> Unit = {},
        tipText: String = ""
    ) {
        mText.value = displayValue
        mOnCancel = onCancel
        mOnOKString = onOKString
        mTipText = tipText
        mShow.value = true
    }
}
